package com.itheima.reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.reggie.dao.CategoryDao;

import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;

import com.itheima.reggie.domain.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;

import com.itheima.reggie.service.SetmealService;
import com.itheima.reggie.service.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl  extends ServiceImpl<CategoryDao, Category> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    public Page<Category> findPage(int page, int pageSize) {
        Page<Category> p = new Page<>(page,pageSize);

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();

        lqw.orderByAsc(Category::getSort);

        Page<Category> categoryPage = categoryDao.selectPage(p, lqw);

        return categoryPage;
    }

    @Override
    public void deleteById(Long ids) {

        //添加条件,根据id进行查询菜品数据
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();

        //sql语句: select count(*) from dish where id =#{ids}
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,ids);
        int count1 = dishService.count(dishLambdaQueryWrapper);
        if (count1>0){
            throw new CustomException("当前分类已经关联了菜品,不能删除");//已经关联了菜品,跑出一个业务异常
        }


        //查询该分类是否已经关联套餐,如果已经关联,抛出一个业务异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,ids);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if (count2 > 0){
            throw new CustomException("当前分类已关联套餐,不能删除");//已经关联套餐，抛出一个业务异常
        }

        //没有关联菜品和套餐正常删除
        categoryDao.deleteById(ids);


    }

    @Override
    public List<Category> findCategory(Category category) {

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();

        lqw.eq(category.getType()!=null,Category::getType,category.getType());

        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> categories = categoryDao.selectList(lqw);

        return categories;
    }


}
